package com.baturu.vin.ford.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf0Input;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * AMF数据处理工具
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AmfUtil {

    private static SerializationContext context = new SerializationContext();

    public static String transformDataObject(byte[] bytes) throws ClassNotFoundException, IOException, IllegalAccessException, NoSuchFieldException {
        int requestUri = bytes[6] * 10 + bytes[7];
        int responseUri = bytes[8 + requestUri] * 10 + bytes[9 + requestUri];
        int startIndex = 8 + requestUri + 2 + responseUri + 4;

        int size = bytes.length - startIndex;
        byte[] realObjectBytes = new byte[size];
        System.arraycopy(bytes, startIndex, realObjectBytes, 0, size);

        Amf0Input amf0Input = new Amf0Input(context);
        amf0Input.setInputStream(new ByteArrayInputStream(realObjectBytes));
        Object o = amf0Input.readObject();

        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(o);
    }
}
